package com.selfdiscipline.ui.screens.statistics

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.selfdiscipline.R
import com.selfdiscipline.ui.navigation.BottomNavigationBar
import com.selfdiscipline.ui.components.charts.BarChart
import com.selfdiscipline.ui.components.charts.ChartData
import com.selfdiscipline.ui.components.charts.HorizontalBarChart
import com.selfdiscipline.ui.components.charts.PieChart
import com.selfdiscipline.ui.components.charts.toUiChartDataList
import kotlin.time.Duration.Companion.minutes

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StatisticsScreen(
    viewModel: StatisticsViewModel = hiltViewModel(),
    navController: NavController
) {
    val uiState by viewModel.uiState.collectAsState()
    var selectedTimeRange by remember { mutableStateOf(TimeRange.WEEKLY) }
    val density = LocalDensity.current
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(text = stringResource(id = R.string.stats_title))
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary,
                    titleContentColor = MaterialTheme.colorScheme.onPrimary
                )
            )
        },
        bottomBar = {
            BottomNavigationBar(navController = navController as NavHostController)
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp)
                .verticalScroll(rememberScrollState())
        ) {
            // 时间范围选择器
            TimeRangeSelector(
                selectedTimeRange = selectedTimeRange,
                onTimeRangeSelected = { 
                    selectedTimeRange = it
                    viewModel.loadStatistics(it)
                }
            )
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 总览卡片
            StatisticsSummaryCard(
                focusTime = uiState.totalFocusTime,
                tasksCompleted = uiState.totalTasksCompleted,
                habitsCompleted = uiState.totalHabitsCompleted,
                timeRange = selectedTimeRange
            )
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 专注时间统计
            StatisticsSection(
                title = stringResource(id = R.string.stats_focus_time)
            ) {
                if (uiState.focusTimeData.isEmpty()) {
                    EmptyDataView()
                } else {
                    BarChart(
                        data = uiState.focusTimeData.toUiChartDataList(),
                        barColor = MaterialTheme.colorScheme.primary,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp)
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 任务完成统计
            StatisticsSection(
                title = stringResource(id = R.string.stats_tasks_completed)
            ) {
                if (uiState.taskCompletionData.isEmpty()) {
                    EmptyDataView()
                } else {
                    BarChart(
                        data = uiState.taskCompletionData.toUiChartDataList(),
                        barColor = MaterialTheme.colorScheme.tertiary,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp)
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 习惯完成统计
            StatisticsSection(
                title = stringResource(id = R.string.stats_habit_completion)
            ) {
                if (uiState.habitCompletionData.isEmpty()) {
                    EmptyDataView()
                } else {
                    HorizontalBarChart(
                        data = uiState.habitCompletionData.toUiChartDataList(),
                        barColor = MaterialTheme.colorScheme.secondary,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp)
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 类别分布
            StatisticsSection(
                title = "专注时间分类"
            ) {
                if (uiState.focusCategoryData.isEmpty()) {
                    EmptyDataView()
                } else {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        PieChart(
                            data = uiState.focusCategoryData.toUiChartDataList(),
                            modifier = Modifier
                                .weight(0.6f)
                                .height(180.dp)
                        )
                        
                        Column(
                            modifier = Modifier
                                .weight(0.4f)
                                .padding(start = 8.dp),
                            verticalArrangement = Arrangement.spacedBy(8.dp)
                        ) {
                            uiState.focusCategoryData.forEach { (category, value, color) ->
                                CategoryLegendItem(
                                    name = category,
                                    color = color,
                                    value = "${(value * 100).toInt()}%"
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TimeRangeSelector(
    selectedTimeRange: TimeRange,
    onTimeRangeSelected: (TimeRange) -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceEvenly
    ) {
        FilterChip(
            selected = selectedTimeRange == TimeRange.DAILY,
            onClick = { onTimeRangeSelected(TimeRange.DAILY) },
            label = { Text(text = stringResource(id = R.string.stats_daily)) },
            colors = FilterChipDefaults.filterChipColors(
                selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
                selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
        
        FilterChip(
            selected = selectedTimeRange == TimeRange.WEEKLY,
            onClick = { onTimeRangeSelected(TimeRange.WEEKLY) },
            label = { Text(text = stringResource(id = R.string.stats_weekly)) },
            colors = FilterChipDefaults.filterChipColors(
                selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
                selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
        
        FilterChip(
            selected = selectedTimeRange == TimeRange.MONTHLY,
            onClick = { onTimeRangeSelected(TimeRange.MONTHLY) },
            label = { Text(text = stringResource(id = R.string.stats_monthly)) },
            colors = FilterChipDefaults.filterChipColors(
                selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
                selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )
    }
}

@Composable
fun StatisticsSummaryCard(
    focusTime: kotlin.time.Duration,
    tasksCompleted: Int,
    habitsCompleted: Int,
    timeRange: TimeRange
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 4.dp
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = when (timeRange) {
                    TimeRange.DAILY -> "今日总览"
                    TimeRange.WEEKLY -> "本周总览"
                    TimeRange.MONTHLY -> "本月总览"
                },
                style = MaterialTheme.typography.titleLarge,
                color = MaterialTheme.colorScheme.onPrimaryContainer
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                SummaryItem(
                    title = "专注时间",
                    value = formatFocusTime(focusTime),
                    modifier = Modifier.weight(1f)
                )
                
                SummaryItem(
                    title = "任务完成",
                    value = "$tasksCompleted 个",
                    modifier = Modifier.weight(1f)
                )
                
                SummaryItem(
                    title = "习惯坚持",
                    value = "$habitsCompleted 个",
                    modifier = Modifier.weight(1f)
                )
            }
        }
    }
}

@Composable
fun SummaryItem(
    title: String,
    value: String,
    modifier: Modifier = Modifier
) {
    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = value,
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            color = MaterialTheme.colorScheme.onPrimaryContainer
        )
        
        Text(
            text = title,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f)
        )
    }
}

@Composable
fun StatisticsSection(
    title: String,
    content: @Composable () -> Unit
) {
    Column {
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.onBackground
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Card(
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surface
            ),
            elevation = CardDefaults.cardElevation(
                defaultElevation = 2.dp
            )
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                content()
            }
        }
    }
}

@Composable
fun CategoryLegendItem(
    name: String,
    color: Color,
    value: String
) {
    Row(
        verticalAlignment = Alignment.CenterVertically
    ) {
        Surface(
            modifier = Modifier
                .padding(end = 8.dp)
                .height(16.dp)
                .width(16.dp),
            color = color,
            shape = MaterialTheme.shapes.small
        ) { }
        
        Text(
            text = name,
            style = MaterialTheme.typography.bodySmall,
            modifier = Modifier.weight(1f)
        )
        
        Text(
            text = value,
            style = MaterialTheme.typography.bodySmall,
            fontWeight = FontWeight.Bold
        )
    }
}

@Composable
fun EmptyDataView() {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(120.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Text(
            text = stringResource(id = R.string.stats_no_data),
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
        )
    }
}

private fun formatFocusTime(duration: kotlin.time.Duration): String {
    val hours = duration.inWholeHours
    val minutes = duration.inWholeMinutes % 60
    
    return if (hours > 0) {
        "$hours 小时 $minutes 分钟"
    } else {
        "$minutes 分钟"
    }
} 